﻿using AutoMapper;
using DTcms.Core.Common.Emum;
using DTcms.Core.DBFactory.Database;
using DTcms.Core.IServices;
using DTcms.Core.Model.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace DTcms.Core.Services
{
    public class ArticleAttachService : BaseService, IArticleAttachService
    {
        private readonly IMapper _mapper;
        private readonly IUserService _userService;
        private readonly IArticleService _articleService;

        public ArticleAttachService(
            IDbContextFactory contentFactory,
            IUserService userService,
            IArticleService articleService,
            IMapper mapper) : base(contentFactory)
        {
            _userService = userService;
            _mapper = mapper;
            _articleService = articleService;
        }

        /// <summary>
        /// 更新下载数量
        /// </summary>
        /// <param name="id">附件主键</param>
        /// <param name="appUser">当前登录用户的信息</param>
        /// <param name="writeAndRead"></param>
        /// <returns></returns>
        public async Task<bool> UpdateDownCount(long id, ApplicationUser appUser, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            ArticleAttach attach = await _context.Set<ArticleAttach>().FirstOrDefaultAsync(t => t.Id == id);
            if (attach == null)
            {
                return false;
            }
            #region 修改下载数量
            attach.DownCount = attach.DownCount + 1;
            #endregion

            #region 添加下载日志
            if (appUser != null)
            {
                MemberAttachLog attachLog = new MemberAttachLog();
                attachLog.AddTime = DateTime.Now;
                attachLog.AttachId = id;
                attachLog.FileName = attach.FileName;
                attachLog.UserId = appUser.Id;
                await _context.Set<MemberAttachLog>().AddAsync(attachLog);
            }
            #endregion
            return await _context.SaveChangesAsync() > 0;
        }
    }
}
